package com.cn.Dao;
import javax.swing.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @Author: cza
 * 数据库备份与还原
 * @Date: 2021/4/11 11:56
 */
public class DbOperateDao {

    private static String root = "root";
    private static String pwd = "WAdl2020";
    private static String dbname = "baozhi";
    private static String Backpath = System.getProperty("user.dir") + "\\Backup\\";
    private static String MySQLtool_path = System.getProperty("user.dir") + "\\MySQLtool";

    public static void dbBackUp(String root, String pwd, String dbName, String backPath, String backName, String MySQLPath) throws Exception {
        String pathSql = backPath + backName;
        System.out.println(pathSql);
        File fileSql = new File(pathSql);
        File f = new File(backPath);
        //创建备份文件夹
        if (!f.exists()) {
            f.mkdirs();
        }
        //创建备份sql文件
        if (!fileSql.exists()) {
            fileSql.createNewFile();
        }
        //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql
        StringBuffer sb = new StringBuffer();
        sb.append("mysqldump");
        sb.append(" -u" + root);
        sb.append(" -p" + pwd);
        sb.append(" " + dbName + " >");
        sb.append(pathSql);
        // System.out.println("cmd命令为："+sb.toString());
        Runtime runtime = Runtime.getRuntime();
        //  System.out.println("开始备份："+dbName);
        Process process = runtime.exec("cmd /k" + "cd MySQLtool" + "&" + sb.toString());
        //   System.out.println("备份成功!");
    }

    /**
     * 恢复数据库
     *
     * @param root
     * @param pwd
     * @param dbName
     * @param filePath mysql -hlocalhost -uroot -p123456 db < /home/back.sql
     */
    public static void dbRestore(String root, String pwd, String dbName, String filePath) {
        StringBuilder sb = new StringBuilder();
        sb.append("mysql");
        //sb.append(" -h");
        sb.append(" -u" + root);
        sb.append(" -p" + pwd);
        sb.append(" " + dbName + " <");
        sb.append(filePath);
        System.out.println("cmd命令为：" + sb.toString());
        Runtime runtime = Runtime.getRuntime();
        System.out.println("开始还原数据");
        try {
            Process process = runtime.exec("cmd /k" + "cd MySQLtool" + "&" + sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("还原成功！");
    }

    public static void doBackup() throws Exception {
        System.out.println(System.getProperty("user.dir") + "\\MySQLtool");
        String backName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".sql";
        DbOperateDao.dbBackUp(root, pwd, dbname, Backpath, backName, MySQLtool_path);
        //dbRestore("root","123456","ks","D://2018-04-30-19-28-28.sql");
    }

    public static void doRecover(String sql) {
        String filepath = Backpath + sql;
        DbOperateDao.dbRestore(root, pwd, dbname, filepath);
    }
}


